package com.mall.mina.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * mina 服务器
 */
@Slf4j
@Component
public class MinaServer{

    IoAcceptor acceptor = new NioSocketAcceptor();
    /**
     * 记录开锁设备 key:ip+“,”+锁id ，value：锁状态 0锁开 1手柄由开变关 2记录已查询 查询完成后 锁可再次将状态变成开锁
     */
    public static final Map<String, String> OPEN_LOCK =new ConcurrentHashMap<>();

    public boolean init(int port){

        try {
            //添加一个过滤器。此过滤器将记录所有信息,例如新创建的会话、接收的消息、发送的消息、会话关闭。
            acceptor.getFilterChain().addLast("logger",new LoggingFilter(this.getClass()));
            //设置编码过滤器（自定义）
            acceptor.getFilterChain().addLast("mycoder",new ProtocolCodecFilter(new CustomProtocolCodecFactory(Charset.forName("UTF-8"))));
            // 设置缓冲区大小
            acceptor.getSessionConfig().setReadBufferSize(3060);
            // 设置读写空闲时间
            acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE,20);
            // 绑定handler
            acceptor.setHandler(new MinaServerHandler());
            // 绑定端口
            acceptor.bind(new InetSocketAddress(port));
            log.info("mina service started successfully, port is {}",port);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return true;
        }
    }
}
